/*
 * Copyright (C) 2010 Tetsuya Yasuda <tetsuyayasuda@gmail.com>
 */
package jp.tyas.libs.lisp;

import java.util.List;
import java.util.ListIterator;

public abstract class Callee
{
    public static boolean debug = false;;

    String name;
    boolean asFunc;

    public Callee (String name, boolean asFunc)
    {
        this.name = name;
        this.asFunc = asFunc;
    }

    public Callee (String name)
    {
        this (name, true);
    }

    public abstract Object call (List args, Context ctx);

    public Object invoke (List args, Context ctx)
    {
        Object res;
        
        if (Callee.debug) Builtin.getStdout(ctx).println ("Callee.invoke(" + name + ") enter");
        
        res = asFunc ? invokeAsFunction (args, ctx) : call (args, ctx);

        if (Callee.debug) Builtin.getStdout(ctx).println ("Callee.invoke(" + name + ") exit");

        return res;
    }

    public Object invokeAsFunction (List args, Context ctx)
    {
        List l = Builtin.newList ();
        ListIterator it = args.listIterator ();
        while (it.hasNext())
            l.add (Builtin.eval(it.next(), ctx));
        return call (l, ctx);
    }

    public String toString ()
    {
        return "<CALLEE: " + name + ">";
    }

    public String getName ()
    {
        return name;
    }
}
